package ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.completeRFC;

import java.sql.ResultSet;
import java.util.ArrayList;

import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.RFCMaker;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.database.DatabaseConnection;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.model.RFC;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.view.mainframe.completeRFCPanel.CompleteRFCPanel;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.view.mainframe.completeRFCPanel.completeRFCSubs.ChooseCompleteRFCDialog;

public class LoadOpenRFCThread extends Thread {

	private CompleteRFCPanel completeRFCPanel;
	private DatabaseConnection connection;
	private ChooseCompleteRFCDialog completeRFCDialog;

	public LoadOpenRFCThread(CompleteRFCPanel completeRFCPanel,
			ChooseCompleteRFCDialog completeRFCDialog) {
		this.completeRFCPanel = completeRFCPanel;
		this.completeRFCDialog = completeRFCDialog;
	}

	@Override
	public synchronized void start() {

		this.connection = new DatabaseConnection();
		this.connection.connect();

		String name = completeRFCPanel.getMainframe().getSignedInUser()
				.getFullName();
		String query = "SELECT * FROM `cms_rfc` WHERE `" + RFC.TC_CHANGEOWNER
				+ "` = '" + name + "' AND `" + RFC.TC_Status + "` = 'open'";

		ResultSet rs = connection.query(query);

		ArrayList<RFC> rfcs = new ArrayList<RFC>();
		int count = 0;
		try {
			while (rs.next()) {
				RFCMaker maker = new RFCMaker();
				rfcs.add(maker.makeanRFC(rs));
				count++;
			}
		} catch (Exception e) {
		}

		if (count == 0) {
			this.completeRFCDialog.getDisplayTable().displayNoElenemt();
		} else {

			this.completeRFCDialog.getDisplayTable().setVisible(false);
			for (RFC rfc : rfcs) {
				this.completeRFCDialog.getDisplayTable().addRFCinTable(rfc);
			}
			this.completeRFCDialog.getDisplayTable().setVisible(true);
		}

		this.completeRFCDialog.getProgress().setVisible(false);
		this.connection.disconnect();

	}

}
